import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApi } from './useApi.js'

// 全局数据状态
const categories = ref([])
const items = ref([])
const pages = ref([])
const hierarchyData = ref([])
const availableCategories = ref([])
const availableItems = ref([])

// 加载状态
const loading = ref({
  categories: false,
  items: false,
  pages: false,
  hierarchy: false
})

// 错误状态
const errors = ref({
  categories: null,
  items: null,
  pages: null,
  hierarchy: null
})

export const useDataStore = () => {
  const api = useApi()
  
  // 计算属性
  const isLoading = computed(() => {
    return Object.values(loading.value).some(state => state)
  })
  
  const hasErrors = computed(() => {
    return Object.values(errors.value).some(error => error !== null)
  })
  
  // 清除错误
  const clearError = (type) => {
    if (type) {
      errors.value[type] = null
    } else {
      Object.keys(errors.value).forEach(key => {
        errors.value[key] = null
      })
    }
  }
  
  // 数据获取方法
  const fetchCategories = async (showMessage = true) => {
    try {
      console.log('🔍 useDataStore - fetchCategories 开始')
      loading.value.categories = true
      clearError('categories')

      const result = await api.getCategories()
      console.log('🔍 useDataStore - API 返回结果:', result)
      categories.value = result.data || []
      console.log('🔍 useDataStore - categories.value 设置为:', categories.value.length, '项')
      console.log('🔍 useDataStore - categories.value 内容:', categories.value.slice(0, 2))

      if (showMessage) {
        ElMessage.success('分类数据加载成功')
      }
    } catch (error) {
      console.error('❌ useDataStore - fetchCategories 失败:', error)
      errors.value.categories = error.message
      if (showMessage) {
        ElMessage.error('获取分类失败')
      }
      console.error('获取分类失败:', error)
    } finally {
      loading.value.categories = false
      console.log('🔍 useDataStore - fetchCategories 完成')
    }
  }
  
  const fetchItems = async (showMessage = true) => {
    try {
      loading.value.items = true
      clearError('items')

      const result = await api.getItems()
      items.value = result.data || []

      if (showMessage) {
        ElMessage.success('项目数据加载成功')
      }
    } catch (error) {
      errors.value.items = error.message
      if (showMessage) {
        ElMessage.error('获取项目失败')
      }
      console.error('获取项目失败:', error)
    } finally {
      loading.value.items = false
    }
  }
  
  const fetchPages = async (showMessage = true) => {
    try {
      loading.value.pages = true
      clearError('pages')

      const result = await api.getPages()
      pages.value = result.data || []

      if (showMessage) {
        ElMessage.success('页面数据加载成功')
      }
    } catch (error) {
      errors.value.pages = error.message
      if (showMessage) {
        ElMessage.error('获取页面失败')
      }
      console.error('获取页面失败:', error)
    } finally {
      loading.value.pages = false
    }
  }
  
  const fetchHierarchyData = async (showMessage = true) => {
    try {
      loading.value.hierarchy = true
      clearError('hierarchy')

      const result = await api.getHierarchyData()
      const pagesData = result.data || []

      // 保存当前的展开状态
      const currentExpandedStates = {}
      hierarchyData.value.forEach((page, pageIndex) => {
        currentExpandedStates[page.id] = {
          expanded: page.expanded,
          categories: {}
        }
        if (page.categories) {
          page.categories.forEach((category, categoryIndex) => {
            currentExpandedStates[page.id].categories[category.id] = category.expanded
          })
        }
      })

      // 为数据添加展开状态，保持之前的展开状态
      hierarchyData.value = pagesData.map(page => ({
        ...page,
        expanded: currentExpandedStates[page.id]?.expanded || false,
        categories: (page.categories || []).map(category => ({
          ...category,
          expanded: currentExpandedStates[page.id]?.categories[category.id] || false,
          items: category.items || []
        }))
      }))

      if (showMessage) {
        ElMessage.success('层级数据加载成功')
      }
    } catch (error) {
      errors.value.hierarchy = error.message
      if (showMessage) {
        ElMessage.error('获取层级数据失败')
      }
      console.error('获取层级数据失败:', error)
    } finally {
      loading.value.hierarchy = false
    }
  }
  
  const fetchAvailableCategories = async () => {
    try {
      const result = await api.getAvailableCategories()
      availableCategories.value = result.data || []
    } catch (error) {
      ElMessage.error('获取可用分类失败')
    }
  }
  
  const fetchAvailableItems = async () => {
    try {
      const result = await api.getAvailableItems()
      availableItems.value = result.data || []
    } catch (error) {
      ElMessage.error('获取可用项目失败')
    }
  }
  
  // 批量数据获取
  const fetchAllData = async () => {
    try {
      const results = await Promise.allSettled([
        fetchCategories(false), // 不显示单个成功消息
        fetchItems(false),
        fetchPages(false),
        fetchHierarchyData(false)
      ])

      // 检查是否有失败的请求
      const failures = results.filter(result => result.status === 'rejected')
      const successes = results.filter(result => result.status === 'fulfilled')

      if (failures.length === 0) {
        ElMessage.success('所有数据加载成功')
      } else if (successes.length > 0) {
        ElMessage.warning(`部分数据加载成功 (${successes.length}/${results.length})`)
      } else {
        ElMessage.error('数据加载失败，请检查网络连接')
      }
    } catch (error) {
      console.error('批量数据获取失败:', error)
      ElMessage.error('数据加载失败')
    }
  }
  
  // 数据操作方法
  const saveCategory = async (categoryData, isEdit = false) => {
    try {
      let result
      if (isEdit) {
        result = await api.updateCategory(categoryData.id, categoryData)
      } else {
        result = await api.createCategory(categoryData)
      }
      
      // 刷新相关数据
      await Promise.allSettled([
        fetchCategories(),
        fetchHierarchyData(),
        fetchAvailableCategories()
      ])
      
      // 返回API响应结果
      return result.data
    } catch (error) {
      ElMessage.error(isEdit ? '分类更新失败' : '分类创建失败')
      throw error
    }
  }
  
  const removeCategory = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除这个分类吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await api.deleteCategory(id)
      ElMessage.success('分类删除成功')
      
      // 异步刷新相关数据，避免页面刷新
      Promise.allSettled([
        fetchCategories(),
        fetchHierarchyData(),
        fetchAvailableCategories()
      ]).then(() => {
        console.log('分类数据已异步刷新')
      }).catch(error => {
        console.error('数据刷新失败:', error)
      })
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('分类删除失败')
        throw error
      }
    }
  }
  
  const saveItem = async (itemData, isEdit = false) => {
    try {
      // 字段名映射：前端字段名 -> 后端字段名
      const fieldMapping = {
        'title': 'name',
        'url': 'external_url',
        // 其他字段保持原名
      }
      
      // 创建映射后的数据对象
      const mappedData = {}
      Object.keys(itemData).forEach(key => {
        const backendFieldName = fieldMapping[key] || key
        mappedData[backendFieldName] = itemData[key]
      })
      
      let result
      if (isEdit) {
        result = await api.updateItem(mappedData.id, mappedData)
        ElMessage.success('项目更新成功')
      } else {
        result = await api.createItem(mappedData)
        ElMessage.success('项目创建成功')
      }
      
      // 刷新相关数据
      await Promise.allSettled([
        fetchItems(),
        fetchHierarchyData(),
        fetchAvailableItems()
      ])
      
      return result
    } catch (error) {
      ElMessage.error(isEdit ? '项目更新失败' : '项目创建失败')
      throw error
    }
  }
  
  const removeItem = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除这个项目吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await api.deleteItem(id)
      ElMessage.success('项目删除成功')
      
      // 异步刷新相关数据，避免页面刷新
      Promise.allSettled([
        fetchItems(),
        fetchHierarchyData(),
        fetchAvailableItems()
      ]).then(() => {
        console.log('项目数据已异步刷新')
      }).catch(error => {
        console.error('数据刷新失败:', error)
      })
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('项目删除失败')
        throw error
      }
    }
  }
  
  const savePage = async (pageData, isEdit = false) => {
    console.log('🔍 useDataStore - savePage 被调用')
    console.log('🔍 useDataStore - pageData:', pageData)
    console.log('🔍 useDataStore - isEdit:', isEdit)
    
    try {
      let response
      if (isEdit) {
        console.log('🔍 useDataStore - 执行更新页面操作 (PUT 请求)')
        console.log('🔍 useDataStore - 页面ID:', pageData.id)
        console.log('🔍 useDataStore - 即将调用 api.updatePage')
        response = await api.updatePage(pageData.id, pageData)
        console.log('✅ useDataStore - api.updatePage 调用完成')
        ElMessage.success('页面更新成功')
      } else {
        console.log('🔍 useDataStore - 执行创建页面操作 (POST 请求)')
        console.log('🔍 useDataStore - 即将调用 api.createPage')
        response = await api.createPage(pageData)
        console.log('✅ useDataStore - api.createPage 调用完成')
        ElMessage.success('页面创建成功')
      }
      
      console.log('✅ useDataStore - 页面保存成功:', response)
      
      // 刷新页面和层级数据
      console.log('🔍 useDataStore - 开始刷新页面和层级数据')
      await Promise.all([
        fetchPages(),
        fetchHierarchyData()
      ])
      console.log('✅ useDataStore - 数据刷新完成')
      
      return response
    } catch (error) {
      console.error('❌ useDataStore - 页面保存失败:', error)
      ElMessage.error(isEdit ? '页面更新失败' : '页面创建失败')
      throw error
    }
  }
  
  const removePage = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除这个页面吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await api.deletePage(id)
      ElMessage.success('页面删除成功')
      
      // 异步刷新相关数据，避免页面刷新
      Promise.allSettled([
        fetchPages(),
        fetchHierarchyData()
      ]).then(() => {
        console.log('页面数据已异步刷新')
      }).catch(error => {
        console.error('数据刷新失败:', error)
      })
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('页面删除失败')
        throw error
      }
    }
  }
  
  // 层级管理方法
  const togglePageExpansion = (pageIndex) => {
    if (hierarchyData.value[pageIndex]) {
      hierarchyData.value[pageIndex].expanded = !hierarchyData.value[pageIndex].expanded
    }
  }
  
  const toggleCategoryExpansion = (pageIndex, categoryIndex) => {
    if (hierarchyData.value[pageIndex]?.categories[categoryIndex]) {
      hierarchyData.value[pageIndex].categories[categoryIndex].expanded = 
        !hierarchyData.value[pageIndex].categories[categoryIndex].expanded
    }
  }
  
  const toggleItemExpansion = (pageIndex, categoryIndex, itemIndex) => {
    if (hierarchyData.value[pageIndex]?.categories[categoryIndex]?.items[itemIndex]) {
      hierarchyData.value[pageIndex].categories[categoryIndex].items[itemIndex].expanded = 
        !hierarchyData.value[pageIndex].categories[categoryIndex].items[itemIndex].expanded
    }
  }
  
  // 关系管理方法
  const manageCategoryPageRelation = async (categoryId, pageId, action = 'add') => {
    try {
      if (action === 'add') {
        await api.addCategoryToPage(pageId, categoryId)
        ElMessage.success('分类添加到页面成功')
      } else {
        await api.removeCategoryFromPage(pageId, categoryId)
        ElMessage.success('分类从页面移除成功')
      }
      
      // 刷新层级数据
      await fetchHierarchyData()
    } catch (error) {
      // 如果是409错误，说明关系已存在，给出更友好的提示
      if (error.message && error.message.includes('409')) {
        ElMessage.warning('该分类已经关联到此页面')
      } else {
        ElMessage.error(action === 'add' ? '添加分类到页面失败' : '从页面移除分类失败')
      }
      throw error
    }
  }
  
  const manageItemCategoryRelation = async (categoryId, itemId, action = 'add') => {
    try {
      if (action === 'add') {
        await api.addItemToCategory(categoryId, itemId)
        ElMessage.success('项目添加到分类成功')
      } else {
        await api.removeItemFromCategory(categoryId, itemId)
        ElMessage.success('项目从分类移除成功')
      }
      
      // 刷新层级数据
      await fetchHierarchyData()
    } catch (error) {
      // 特殊处理409冲突错误（关系已存在）
      if (error.response?.status === 409 && action === 'add') {
        ElMessage.warning('该项目已与分类关联')
        // 即使关系已存在，也刷新数据以确保UI状态正确
        await fetchHierarchyData()
        return
      }
      
      ElMessage.error(action === 'add' ? '添加项目到分类失败' : '从分类移除项目失败')
      throw error
    }
  }
  
  return {
    // 数据状态
    categories,
    items,
    pages,
    hierarchyData,
    availableCategories,
    availableItems,
    
    // 加载和错误状态
    loading,
    errors,
    isLoading,
    hasErrors,
    clearError,
    
    // 数据获取方法
    fetchCategories,
    fetchItems,
    fetchPages,
    fetchHierarchyData,
    fetchAvailableCategories,
    fetchAvailableItems,
    fetchAllData,
    
    // 数据操作方法
    saveCategory,
    removeCategory,
    saveItem,
    removeItem,
    savePage,
    removePage,
    
    // 层级管理
    togglePageExpansion,
    toggleCategoryExpansion,
    toggleItemExpansion,
    
    // 关系管理
    manageCategoryPageRelation,
    manageItemCategoryRelation
  }
}